#!/usr/bin/env python3
# coding=utf-8
import requests
import shutil
import urllib.parse as urlparse  # import urlparse # python2


class cachefiler:

    def __init__(self, host='127.0.0.1', port=9333, protocol='http'):

        self.host = host
        self.port = port
        self.protocol = protocol
        self.url = '%s:%d' % (host, port)
        self.url = '%s://' % self.protocol + self.url

    def put(self, filename, remote_path):
        url = urlparse.urljoin(self.url, remote_path)
        print(url)
        with open(filename, 'rb') as up_file:
            file = {'file': up_file}
            rsp = requests.post(url, files=file)
            if rsp.status_code == requests.codes.ok or rsp.status_code ==201:
                print("finished " + str(rsp.status_code))

            else:
                print("status:" + str(rsp.status_code))

    def get(self, filename, remote_path):
        url = urlparse.urljoin(self.url, remote_path)
        print(url)
        rsp = None
        rsp = requests.get(url)
        print(rsp.status_code)
        return(rsp.status_code)
        # try:
        #     rsp = requests.get(url)
        #     if rsp.status_code == requests.codes.ok:
        #         with open(filename, 'wb') as down_img:
        #             shutil.copyfile(rsp.raw, down_img)
        #         print("finished " + str(rsp.status_code))
        #     else:
        #         print("failed" + str(rsp.status_code))
        # except Exception as e:
        #     print(rsp)
        #     print("error getting %s. e:%s" % (url, e))


if __name__ == '__main__':
    print("main")
    # cl = cachefiler(host="192.168.12.122", port=8890)
    cl = cachefiler(host='filter', port=8888)
    # cl = cachefiler(host='127.0.0.1', port=8888)
    savefile_path = "imgtest.jpg"
    localfile_path = "img1.jpg"
    server_path = ""
    # server_path = "/0/llsenhdd6,jpg"
    # cl.get(savefile_path, server_path)
    cl.put(localfile_path, server_path)
    # main()
